package com.example.filefusion.controller;

import com.example.filefusion.entity.FileChunk;
import com.example.filefusion.service.ChunkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/chunk")
public class ChunkController {

    private static final Logger logger = LoggerFactory.getLogger(ChunkController.class);

    @Autowired
    private ChunkService chunkService;

    /**
     * 上传文件分片
     * @param file 文件分片
     * @param chunk 分片信息
     * @return 上传结果
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<?> uploadChunk(@RequestParam("file") MultipartFile file,
                                         @RequestParam("identifier") String identifier,
                                         @RequestParam("chunkNumber") long chunkNumber,
                                         @RequestParam("totalChunks") long totalChunks,
                                         @RequestParam("chunkSize") long chunkSize,
                                         @RequestParam("totalSize") long totalSize,
                                         @RequestParam("filename") String filename,
                                         @RequestParam("relativePath") String relativePath) {
        try {
            logger.info("开始上传文件分片: identifier={}, chunkNumber={}, filename={}", identifier, chunkNumber, filename);
            
            FileChunk chunk = new FileChunk();
            chunk.setIdentifier(identifier);
            chunk.setChunkNumber(chunkNumber);
            chunk.setTotalChunks(totalChunks);
            chunk.setChunkSize(chunkSize);
            chunk.setTotalSize(totalSize);
            chunk.setFilename(filename);
            chunk.setRelativePath(relativePath);

            boolean result = chunkService.uploadChunk(file, chunk);
            if (result) {
                logger.info("文件分片上传成功: identifier={}, chunkNumber={}, filename={}", identifier, chunkNumber, filename);
                return ResponseEntity.ok().body("{\"message\": \"分片上传成功\"}");
            } else {
                logger.warn("文件分片上传失败: identifier={}, chunkNumber={}, filename={}", identifier, chunkNumber, filename);
                return ResponseEntity.badRequest().body("{\"message\": \"分片上传失败\"}");
            }
        } catch (Exception e) {
            logger.error("文件分片上传异常: identifier={}, chunkNumber={}, filename={}, error={}", identifier, chunkNumber, filename, e.getMessage(), e);
            return ResponseEntity.badRequest().body("{\"message\": \"分片上传异常: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 检查分片是否存在
     * @param chunk 分片信息
     * @return 检查结果
     */
    @GetMapping("/check")
    @ResponseBody
    public ResponseEntity<?> checkChunk(@RequestParam("identifier") String identifier,
                                        @RequestParam("chunkNumber") long chunkNumber,
                                        @RequestParam("totalChunks") long totalChunks,
                                        @RequestParam("chunkSize") long chunkSize,
                                        @RequestParam("totalSize") long totalSize,
                                        @RequestParam("filename") String filename,
                                        @RequestParam("relativePath") String relativePath) {
        try {
            logger.info("开始检查文件分片是否存在: identifier={}, chunkNumber={}, filename={}", identifier, chunkNumber, filename);
            
            FileChunk chunk = new FileChunk();
            chunk.setIdentifier(identifier);
            chunk.setChunkNumber(chunkNumber);
            chunk.setTotalChunks(totalChunks);
            chunk.setChunkSize(chunkSize);
            chunk.setTotalSize(totalSize);
            chunk.setFilename(filename);
            chunk.setRelativePath(relativePath);

            boolean exists = chunkService.checkChunk(chunk);
            if (exists) {
                logger.info("文件分片存在: identifier={}, chunkNumber={}, filename={}", identifier, chunkNumber, filename);
                return ResponseEntity.ok().body("{\"exists\": true}");
            } else {
                logger.info("文件分片不存在: identifier={}, chunkNumber={}, filename={}", identifier, chunkNumber, filename);
                return ResponseEntity.ok().body("{\"exists\": false}");
            }
        } catch (Exception e) {
            logger.error("检查文件分片异常: identifier={}, chunkNumber={}, filename={}, error={}", identifier, chunkNumber, filename, e.getMessage(), e);
            return ResponseEntity.badRequest().body("{\"message\": \"检查分片异常: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 合并分片
     * @param chunk 分片信息
     * @return 合并结果
     */
    @PostMapping("/merge")
    @ResponseBody
    public ResponseEntity<?> mergeChunks(@RequestParam("identifier") String identifier,
                                         @RequestParam("totalChunks") long totalChunks,
                                         @RequestParam("chunkSize") long chunkSize,
                                         @RequestParam("totalSize") long totalSize,
                                         @RequestParam("filename") String filename,
                                         @RequestParam("relativePath") String relativePath) {
        try {
            logger.info("开始合并文件分片: identifier={}, totalChunks={}, filename={}", identifier, totalChunks, filename);
            
            FileChunk chunk = new FileChunk();
            chunk.setIdentifier(identifier);
            chunk.setTotalChunks(totalChunks);
            chunk.setChunkSize(chunkSize);
            chunk.setTotalSize(totalSize);
            chunk.setFilename(filename);
            chunk.setRelativePath(relativePath);

            String fileName = chunkService.mergeChunks(chunk);
            logger.info("文件分片合并成功: identifier={}, filename={}, mergedFileName={}", identifier, filename, fileName);
            return ResponseEntity.ok().body("{\"message\": \"合并成功\", \"fileName\": \"" + fileName + "\"}");
        } catch (Exception e) {
            logger.error("合并文件分片异常: identifier={}, filename={}, error={}", identifier, filename, e.getMessage(), e);
            return ResponseEntity.badRequest().body("{\"message\": \"合并分片异常: " + e.getMessage() + "\"}");
        }
    }
}